package com.nsgf.library.ui.page.fragment;

import static com.nsgf.library.ui.page.home.HomeFragment.DBXC;
import static com.nsgf.library.ui.page.home.HomeFragment.JCJC;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.MessageBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderBean;
import com.nsgf.library.data.repository.DataRepository;
import com.nsgf.library.data.response.DataResult;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.FragmentNagfManagerListBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.ui.adapter.ManagerListAdapter;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.manager.ManagerWorkOrderDetailsActivity;
import com.nsgf.library.ui.page.manager.WorkCreateActivity;
import com.nsgf.library.ui.page.manager.WorkOrderAlreadyActivity;
import com.nsgf.library.ui.page.manager.WorkOrderExamineAlreadyActivity;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.disposables.Disposable;

public class ManagerPageFragment extends BaseFragment {
    MessageFragmentStates mStates;

    private ManagerListAdapter mAdapter;

    private AccountRequester mAccountRequester;

    public static ManagerPageFragment newInstance(int type) {
        ManagerPageFragment messageFragment = new ManagerPageFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        messageFragment.setArguments(bundle);
        return messageFragment;
    }

    private int getType() {
        return getArguments().getInt("type");
    }

    @Override
    protected void initViewModel() {

        mStates = getActivityScopeViewModel(MessageFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    public void setSources(String sources) {
        this.sources = sources;
        getDatas(sources, startTime, endTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("warning".equals(event.getMsg()))
            mBinding.smartRefreshLayout.autoRefresh();
    }

    private FragmentNagfManagerListBinding mBinding;

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new ManagerListAdapter(getContext());

        return new DataBindingConfig(R.layout.fragment_nagf_manager_list, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (FragmentNagfManagerListBinding) getBinding();
        EventBus.getDefault().register(this);
        mBinding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getDatas(sources, startTime, endTime);

            }
        });
//        mAccountRequester.workOrderList(UserInfo.getInstance().getProjectCode(), getType(), "", "", "");

        getDatas("", "", "");

        if (0 == getType()) {
            mBinding.tvNsgfManagerD.setVisibility(View.VISIBLE);
            mBinding.tvNsgfManagerY.setVisibility(View.GONE);
        } else {
            mBinding.tvNsgfManagerY.setVisibility(View.VISIBLE);
            mBinding.tvNsgfManagerD.setVisibility(View.GONE);
        }
        mAdapter.setOnItemClickListener(new BaseDataBindingAdapter.OnItemClickListener<WorkOrderBean>() {
            @Override
            public void onItemClick(int viewId, WorkOrderBean item, int position) {
//
//                startActivity(new Intent()
//                    .putExtra("orderCode", item.getOrderCode())
//                    .setClass(getActivity(), WorkOrderMapActivity.class));
//
                Intent intent;

                if (item.getWorkOrderSource() > 3 && item.getWorkOrderSource() < 7) {
                    intent = new Intent(getActivity(), WorkCreateActivity.class);
                    intent.putExtra("info", item);
                    intent.putExtra("title", "工单详情");

                } else {
                    if (1 == item.getIsResponsibleBy()) {
                        intent = new Intent(getActivity(), WorkOrderExamineAlreadyActivity.class);
                    } else {
                        if (0 == getType())
                            intent = new Intent(getActivity(), ManagerWorkOrderDetailsActivity.class);
                        else
                            intent = new Intent(getActivity(), WorkOrderAlreadyActivity.class);
                    }
                    intent.putExtra("title", item.getWorkOrderSourceSrc());
                    intent.putExtra("orderCode", item.getOrderCode());
                    intent.putExtra("workOrderSource", item.getWorkOrderSource());
                    intent.putExtra("isResponsibleBy", item.getIsResponsibleBy());
                }
                startActivity(intent);
            }
        });

    }

    private String search;

    public void search(String search) {
        this.search = search;
        getDatas(sources, startTime, endTime);
    }

    private int number = 0;

    /**
     * @param sources   工单来源(1:工程巡查 2:任务计划 3:异常问题)
     * @param startTime
     * @param endTime
     */
    private void getDatas(String sources, String startTime, String endTime) {
        String patrolType = null;
        if ("1".equals(sources)) {
            patrolType = JCJC;
        } else if ("2".equals(sources)) {
            patrolType = DBXC;
            sources = "1";
        } else if ("4".equals(sources)) {
            sources = "2";
        }
        DataRepository.getInstance()
                .workOrderList(UserInfo.getInstance().getProjectCode(),
                        getType(),
                        sources,
                        startTime,
                        endTime,
                        search,
                        patrolType)
                .subscribe(new io.reactivex.Observer<DataResult<ResponseStatus<List<WorkOrderBean>>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(DataResult<ResponseStatus<List<WorkOrderBean>>> dataResult) {
                        if (dataResult.getResponseStatus().isSuccess()) {
                            if (dataResult.getResult().getResponseCode() == 200) {
                                mAdapter.submitList(dataResult.getResult().getData());

                                if (dataResult.getResult().getData().size() > 0) {
                                    mBinding.notdata.setVisibility(View.GONE);
                                } else {
                                    mBinding.notdata.setVisibility(View.VISIBLE);
                                }

                                if (0 == getType()) {

                                    EventMsg eventMsg = new EventMsg();
                                    eventMsg.setMsg("badge");
                                    eventMsg.setContent(String.valueOf(dataResult.getResult().getData().size()));
                                    RxBus.get().post(eventMsg);

                                }

                            } else {

                                if (401 == dataResult.getResult().getResponseCode()) {
                                    UserInfo.getInstance().clearUserInfo();
                                    getActivity().finish();
                                }
                                ToastUtils.showLongToast(dataResult.getResult().getMsg());
                            }

                        } else {
                            ToastUtils.showLongToast(getErrorMsg(dataResult.getResponseStatus().getE()));
                        }
                        mBinding.smartRefreshLayout.finishRefreshWithNoMoreData();

                    }

                    @Override
                    public void onError(Throwable e) {

                        mBinding.smartRefreshLayout.finishRefresh();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public static class MessageFragmentStates extends StateHolder {

        public final State<String> time = new State<>("");
        public final State<String> timey = new State<>("");

        public final State<List<WorkOrderBean>> list = new State<>(new ArrayList<>());

        public final State<Boolean> loadingVisible = new State<>(false);

    }


    private String startTime = "";
    private String endTime = "";
    private String sources = "";

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public class ClickProxy {

        public void autoRefresh() {
            mBinding.smartRefreshLayout.autoRefresh();
        }

        public void screenType() {
            final ArrayList<String> list = new ArrayList<>();
            list.add("全部");
            list.add("经常检查");
            list.add("大坝巡查");
            list.add("异常问题");
            list.add("任务计划");
            OptionsPickerView<String> mOptionsPickerView = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    if (0 == options1) {
                        setSources("");
                        mBinding.tvTitleScree.setText("");
                    } else {
                        mBinding.tvTitleScree.setText(list.get(options1));
                        setSources(String.valueOf(options1));
                    }
                }
            }).build();
            mOptionsPickerView.setPicker(list);
            mOptionsPickerView.show();
        }

        public void screenTime() {

            startTime = "";
            endTime = "";

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    startTime = ymd.format(date);

                    new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            endTime = ymd.format(date);

                            getDatas(sources, startTime, endTime);

                            if (0 == getType())
                                mStates.time.set(startTime + "-" + endTime);
                            else
                                mStates.timey.set(startTime + "-" + endTime);
                        }
                    }).isCyclic(false)
                            .setRangDate(null, null)
                            .setType(type)
                            .setDate(Calendar.getInstance()).build().show();


                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setDate(Calendar.getInstance()).build();

            mTimePickerView.show();


        }

        public void clearTime() {

            if (0 == getType())
                mStates.time.set("");
            else
                mStates.timey.set("");

            startTime = "";
            endTime = "";

            getDatas(sources, "", "");
        }
    }

}
